const { request, getImageUrl } = require("/utils");
import { TradeStatusText } from '/constants';
Page({
    data: {
        tabList: [{
                name: '全部',
                active: true
            },
            {
                name: '已支付',
                status: 2
            },
            {
                name: '待支付',
                status: 1
            },
            {
                name: '已取消',
                status: 0
            },
        ],
        page: 1,
        pageSize: 10,
        orderList: []
    },
    onLoad() {
        my.setCanPullDown({ canPullDown: false });
    },
    onShow() {
        this.setData({
            orderList: [],
            page: 1
        });
        this.getList();
    },
    async getList() {
        const status = this.getCurrentStatus();
        const { page, pageSize, orderList } = this.data;
        const params = { page, pageSize };
        if (status !== undefined) params.status = status;
        const { code, data } = await request.get('/miniapp/order/list', { params });
        if (code !== 200) return;
        this.setData({
            orderList: orderList.concat(data.map(item => ({
                ...item,
                createdTimeString: new Date(item.createdTime).toLocaleString(),
                statusString: TradeStatusText[item.status],
                price: (item.price / 100).toFixed(2),
                orderItems: item.orderItems.map(orderItem => ({
                    ...orderItem,
                    skuImage: orderItem.sku.images.length ? getImageUrl(orderItem.sku
                        .images[
                            0]) : getImageUrl(orderItem.goods.cover),
                    sku: { ...orderItem.sku, price: (orderItem.sku.price / 100).toFixed(2) }
                })),
                amount: item.orderItems.reduce((pre, item) => pre + item.amount, 0)
            })))
        })
    },
    tapTab({ target: { dataset: { index } } }) {
        const { tabList } = this.data;
        tabList.forEach((item, itemIndex) => item.active = (index === itemIndex));
        this.setData({
            page: 1,
            tabList,
            orderList: []
        });
        this.getList();
    },
    getCurrentStatus() {
        const { status } = this.data.tabList.find(item => item.active);
        return status;
    },
    scrollToLower() {
        this.setData({
            page: this.data.page + 1
        });
        this.getList();
    },
    tapOrderItem({ target: { dataset: { alipayTradeNo } } }) {
        my.navigateTo({ url: '/pages/orderDetail/orderDetail?alipayTradeNo=' + alipayTradeNo });
    }
});